package com.gexin.common;

import com.gexin.common.utils.ExportDocBeetl;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Log;
import com.xuxueli.poi.excel.ExcelExportUtil;
import org.beetl.core.resource.FileResourceLoader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Excel导入和导出
 *
 * @author W.cl
 * @version 1.0
 */
public class ExcelUtils {
	private static final Log log = Log.getLog(ExcelUtils.class);

	@SuppressWarnings("unused")
	private static final FileResourceLoader resourceLoader = new FileResourceLoader(PathKit.getRootClassPath(), "utf-8");

	/**
	 * 导出Excel
	 *
	 * @param response
	 * @param request
	 * @param fileName
	 * @param dataList Excel数据
	 */
	public static void exportDocument(HttpServletResponse response, HttpServletRequest request, String fileName, List<?>... dataList) {
		fileName = ExportDocBeetl.EnCodeFileNmae(request, fileName);
		response.reset();
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
		OutputStream toClient = null;
		try {
			toClient = new BufferedOutputStream(response.getOutputStream());
			//将excel的字节数据写入到浏览器的输出流
			toClient.write(ExcelExportUtil.exportToBytes(dataList));
			//关闭流
		} catch (IOException e) {
			e.printStackTrace();
			log.error("向客户端发送文件失败：", e);
		} finally {
			if (toClient != null) {
				try {
					toClient.flush();
					toClient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}


}
